/*加载css文件*/
function leafletLoadCss(path) {
    if(!path || path.length === 0){
        throw new Error('argument "path" is required !');
    }
    var head = document.getElementsByTagName('head')[0];
    var link = document.createElement('link');
    link.href = path;
    link.rel = 'stylesheet';
    link.type = 'text/css';
    link.onload = ()=>{

    };
    head.appendChild(link);
}
/*发送ajax*/
function leafletAjax(url,type,callback) {
    var xhr=null;
    if(window.XMLHttpRequest){
        xhr=new XMLHttpRequest();
    }else{
        xhr=new ActiveXObject('Microsoft.XMLHTTP');
    }
    xhr.open(type,url,false);
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            if(xhr.status==200){
                var info = xhr.responseText;
                if(typeof callback == 'function')
                {
                    callback(url,info);
                }
            }
        }
    }
    xhr.send(null);
}
function callbackScriptEval(url,info) {
    //console.log(url);
    try{
        eval(info);
    }catch (e) {
        console.log(url+'eval错误',e);
    }
}
/*加载所需css和js*/
function loadNeedCssJs() {
    var h5loadCssJsUrlData = [
        {type:'css',url:'/assets/addons/wleaflet/leaflet/leaflet.css',callback:function () {}},
        {type:'css',url:'/assets/addons/wleaflet/leaflet/plugins/leaflet-geoman-free/leaflet-geoman.css',callback:function () {}},
        {type:'js',url:'/assets/addons/wleaflet/leaflet/leaflet.js',callback:callbackScriptEval},
        {type:'js',url:'/assets/addons/wleaflet/leaflet/plugins/proj4/proj4.js',callback:callbackScriptEval},
        {type:'js',url:'/assets/addons/wleaflet/leaflet/plugins/proj4/proj4leaflet.min.js',callback:callbackScriptEval},
        {type:'js',url:'/assets/addons/wleaflet/leaflet/leaflet.ChineseTmsProviders.js',callback:callbackScriptEval},
        {type:'js',url:'/assets/addons/wleaflet/leaflet/leaflet.mapCorrection.js',callback:callbackScriptEval},
        {type:'js',url:'/assets/addons/wleaflet/leaflet/plugins/leaflet-geoman-free/leaflet-geoman.min.js',callback:callbackScriptEval},
        {type:'js',url:'/index.php/addons/wleaflet/index/getConfig',callback:function (res,info) {
                var json = info?JSON.parse(info):{}; //加载配置资源
                systemSetConfig = json.config;
            }}
    ];
    //加载所需js文件
    var opeData = (typeof isH5loadCssJsUrlData != "undefined")?h5loadCssJsUrlData:requireloadCssJsUrlData;
    opeData.forEach(function (item) {
        item.url = item.url+'?time='+ (new Date).getTime()
        if(item.type == 'js')
        {
            leafletAjax(item.url,'GET',item.callback);
        }else if(item.type == 'css')
        {
            leafletLoadCss(item.url);
        }

    })
}
const wLeafletTiandiMap = 'tiandimap';
const wLeafletGaodemap = 'gaodemap';
const wLeafletTencentmap = 'tencentmap';
const wLeafletBaidumap = 'baidumap';
if(typeof isH5loadCssJsUrlData != "undefined")
{
    var systemSetConfig = {};
    loadNeedCssJs();
}else{
    //默认走require的加载方式
    var systemSetConfig = Config.wleaflet;
}
const wLeaflet = {
    map:null,
    params:{
        dom:'map', //默认初始化div
        defaultLayer:systemSetConfig.defaultLayer?systemSetConfig.defaultLayer:wLeafletTiandiMap, //默认组件
        defaultLayerList:{
            '高德地图':wLeafletGaodemap,
            '天地图':wLeafletTiandiMap,
            '腾讯地图':wLeafletTencentmap,
            '百度地图':wLeafletBaidumap
        },
        baseLayers:{}, //添加可切换图层
        useDefaultLayerList:systemSetConfig.useDefaultLayerList?systemSetConfig.useDefaultLayerList:[],
        defaultCenter:systemSetConfig.defaultCenter?systemSetConfig.defaultCenter:[39.919990,116.456270],
        zoomBase:systemSetConfig.zoomBase?systemSetConfig.zoomBase:14,
        zoomMin:5,
        zoomMax:18,
        gaodeKey:systemSetConfig.gaodeKey?systemSetConfig.gaodeKey:'', //高德key
        gaodeSecurityJsCode:systemSetConfig.gaodeSecurityJsCode?systemSetConfig.gaodeSecurityJsCode:'', //秘钥
        tdtKey:systemSetConfig.tdtKey?systemSetConfig.tdtKey:'',
        tencentKey:systemSetConfig.tencentKey?systemSetConfig.tencentKey:'',
        baiduKey:systemSetConfig.baiduKey?systemSetConfig.baiduKey:'',
        markerImage:'/assets/addons/wleaflet/leaflet/images/marker.png',
        markerImageSize:[25, 30],
        mapClickCallbackFunc:null,
        polyline:null,
        TdtNormalm:null,
        TdtNormala:null,
        TdtBaseLayer:null,
        GaodeNormalm:null,
        GaodeBaseLayer:null,
        TencentNormalm:null,
        TencentBaseLayer:null,
        BaiduNormalm:null,
        BaiduBaseLayer:null,
        mapPmDrawParams:{
            jsClass:'', //当前绘画的类型
            drawMaxCount:-1, //最多允许获取画多少个点
        }
    },
    getParams:function(){
        return this.params;
    },
    setTdtNormalm:function()
    {
        this.params.TdtNormalm = L.tileLayer.chinaProvider('TianDiTu.Normal.Map', { maxZoom: this.params.zoomMax, minZoom: this.params.zoomMin, key: this.params.tdtKey });
        this.params.TdtNormala = L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion', { maxZoom: this.params.zoomMax, minZoom: this.params.zoomMin, key: this.params.tdtKey });
        this.params.TdtBaseLayer = L.layerGroup([this.params.TdtNormalm,this.params.TdtNormala]);//天地图基础图层
    },
    setGaodeNormalm:function(){
        this.params.GaodeNormalm = L.tileLayer.chinaProvider('GaoDe.Normal.Map', { maxZoom: this.params.zoomMax, minZoom: this.params.zoomMin, key: this.params.gaodeKey});
        this.params.GaodeBaseLayer = [this.params.GaodeNormalm];//高德地图基础图层*/
    },
    setTencentNormalm:function(){
        this.params.TencentNormalm = L.tileLayer.chinaProvider('Tencent.Normal.Map', { maxZoom: this.params.zoomMax, minZoom: this.params.zoomMin, key: this.params.tencentKey});
        this.params.TencentBaseLayer = [this.params.TencentNormalm];//腾讯地图基础图层*/
    },
    setBaiduNormalm:function(){
        this.params.BaiduNormalm = L.tileLayer.chinaProvider('Baidu.Normal.Map', { maxZoom: this.params.zoomMax, minZoom: this.params.zoomMin, key: this.params.baiduKey});
        this.params.BaiduBaseLayer = [this.params.BaiduNormalm];//百度地图基础图层*/
    },
    //初始化基础图层
    initBaseLayer:function(){
        var _this = this;
        var useDefaultLayerList = _this.params.useDefaultLayerList;
        if(useDefaultLayerList.length > 0)
        {
            useDefaultLayerList.forEach(function (item) {
                _this.initBaseLayerFunc(item,true);
            })
        }
        if(useDefaultLayerList.indexOf(_this.params.defaultLayer) < 0)
        {
            _this.initBaseLayerFunc(_this.params.defaultLayer);
        }

    },
    initBaseLayerFunc:function(mapKey,appendBaseLayer){
        switch (mapKey) {
            case wLeafletTiandiMap:
                this.setTdtNormalm();
                if(appendBaseLayer)
                {
                    this.params.baseLayers['天地图'] = this.params.TdtBaseLayer;
                }
                break;
            case wLeafletGaodemap:
                this.setGaodeNormalm();
                if(appendBaseLayer)
                {
                    this.params.baseLayers['高德地图'] = this.params.GaodeNormalm;
                }
                break;
            case wLeafletTencentmap:
                this.setTencentNormalm();
                if(appendBaseLayer)
                {
                    this.params.baseLayers['腾讯地图'] = this.params.TencentNormalm;
                }
                break;
            case wLeafletBaidumap:
                this.setBaiduNormalm();
                if(appendBaseLayer)
                {
                    this.params.baseLayers['百度地图'] = this.params.BaiduNormalm;
                }
                break;
        }
    },
    init:function(config){
        config = config?config:{};
        var _this = this;
        this.initBaseLayer();
        var useMapType = _this.params.defaultLayer;
        if(config.maptype)
        {
            _this.params.defaultLayer = config.maptype;
            useMapType = config.maptype;
        }
        var initParams = this.params;
        var initMapLayers = null;
        switch (useMapType) {
            case wLeafletTiandiMap:
                initMapLayers = initParams.TdtBaseLayer;
                break;
            case wLeafletGaodemap:
                initMapLayers = initParams.GaodeBaseLayer;
                break;
            case wLeafletTencentmap:
                initMapLayers = initParams.TencentBaseLayer;
                break;
            case wLeafletBaidumap:
                initMapLayers = initParams.BaiduBaseLayer;
                break;
        }
        if(!initMapLayers)
        {
            console.log('未获取到底层地图');
            return false;
        }
        var lat = (config.lat && config.lat > 0)?config.lat:initParams.defaultCenter[0];
        var lng = (config.lng && config.lng > 0)?config.lng:initParams.defaultCenter[1];
        if(useMapType == wLeafletBaidumap)
        {
            var useCrs = L.CRS.Baidu;
        }else{
            var useCrs = L.CRS.EPSG3857;
        }
        if(config.dom)
        {
            _this.params.dom = config.dom;
        }
        _this.map = L.map(_this.params.dom, {
            //crs:L.CRS.EPSG3857,
            crs: useCrs,
            center: [lat, lng],
            zoom: config.zoomBase?config.zoomBase:initParams.zoomBase,
            layers:initMapLayers,
            zoomControl: false,
            scaleControl: true
        });
        _this.map.addEventListener('zoom',function (res) {
            if(typeof config.zoomSaveFunc == 'function')
            {
                config.zoomSaveFunc(_this.map.getZoom()); //监听zoom等级发生变化时候的办法
            }
        })
        L.control.zoom({
            zoomInTitle: '放大',
            zoomOutTitle: '缩小'
        }).addTo(_this.map);
        if(typeof config.zoomSaveFunc == 'function')
        {
            config.zoomSaveFunc(_this.map.getZoom()); //监听zoom等级发生变化时候的办法
        }
        //创建底层切换
        var baseLayers = this.params.baseLayers;
        var overlays = {};
        if(_this.params.useDefaultLayerList.length > 1)
        {
            L.control.layers(baseLayers, overlays).addTo(_this.map);
        }
        //底层地图切换事件
        _this.map.on('baselayerchange',function (res) {
            //if(_this.defaultLayerList)
            var defaultLayerList = _this.params.defaultLayerList;
            if(defaultLayerList[res.name])
            {
                _this.params.defaultLayer = defaultLayerList[res.name];
            }
            if(typeof config.baseLayerChangeFunc == 'function')
            {
                config.baseLayerChangeFunc({
                    changeMapType:_this.params.defaultLayer,
                    zoom:_this.map.getZoom(),
                    mapDom:_this.params.dom
                });
            }
        })
        //加载折线插件之后
        _this.map.pm.setLang('zh'); //使用中国语言
        _this.map.on('pm:drawstart', ({ workingLayer }) => {
            //console.log('workingLayer',workingLayer)
            workingLayer.on('pm:vertexadded', (e) => {
                var drawMaxCount = _this.params.mapPmDrawParams.drawMaxCount;
                if( drawMaxCount > 0 && e.layer._latlngs.length >= drawMaxCount)
                {
                    _this.map.pm.Draw[_this.params.mapPmDrawParams.jsClass]._finishShape();
                }
            });
        });
        return this;
    },
    //加载其他外部api
    otherApi:{
        params:{
            loadTiandiMapJs:{
                status:false,
                url:'https://api.tianditu.gov.cn/api?v=4.0&tk={r_tk}',
                mapDiv:null
            },
            loadTencentMapJs:{
                status:false,
                url:'https://map.qq.com/api/gljs?v=1.exp&key={r_tk}&libraries=service',
                mapDiv:null
            },
            loadGaodeMapJs:{
                status:false,
                url:'https://webapi.amap.com/maps?v=1.4.15&key={r_tk}',
                mapDiv:null
            },
            loadBaiduMapJs:{
                status:false,
                url:'https://api.map.baidu.com/getscript?v=2.0&ak={r_tk}&services=',
                mapDiv:null
            },
        },
        loadJs:function(src,callback) {
            return new Promise((resolve, reject)=>{
                let script = document.createElement('script');
                script.type = "text/javascript";
                script.onload = ()=>{
                    callback();
                };
                script.onerror = ()=>{
                    console.log('加载js失败')
                };
                script.src= src;
                document.getElementsByTagName('body')[0].appendChild(script);
            });
        },
        //通过经纬度获取逆地址解析
        getLocationBylatlng:function(latlng,callback){
            var _this = this;
            let defaultLayer = wLeaflet.params.defaultLayer;
            switch (defaultLayer) {
                case wLeafletTiandiMap:
                    _this.tiandiMapFunc.getLocation(latlng,function (res) {
                        res.useMapType = defaultLayer;
                        callback(res);
                    });
                    break;
                case wLeafletGaodemap:
                    _this.gaodeMapFunc.getLocation(latlng,function (res) {
                        res.useMapType = defaultLayer;
                        callback(res);
                    });
                    break;
                case wLeafletTencentmap:
                    _this.tencentMapFunc.getLocation(latlng,function (res) {
                        res.useMapType = defaultLayer;
                        callback(res);
                    });
                    break;
                case wLeafletBaidumap:
                    _this.baiduMapFunc.getLocation(latlng,function (res) {
                        res.useMapType = defaultLayer;
                        callback(res);
                    });
                    break;
            }
        },
        //通过标题搜索
        getLocationSearch:function(title,callback){
            var _this = this;
            let defaultLayer = wLeaflet.params.defaultLayer;
            switch (defaultLayer) {
                case wLeafletTiandiMap:
                    _this.tiandiMapFunc.getLocationSearch(title,function (res) {
                        callback({
                            datalist:res,
                            useMapType:defaultLayer
                        });
                    });
                    break;
                case wLeafletGaodemap:
                    _this.gaodeMapFunc.getLocationSearch(title,function (res) {
                        callback({
                            datalist:res,
                            useMapType:defaultLayer
                        });
                    });
                    break;
                case wLeafletTencentmap:
                    _this.tencentMapFunc.getLocationSearch(title,function (res) {
                        callback({
                            datalist:res,
                            useMapType:defaultLayer
                        });
                    });
                    break;
                case wLeafletBaidumap:
                    _this.baiduMapFunc.getLocationSearch(title,function (res) {
                        callback({
                            datalist:res,
                            useMapType:defaultLayer
                        });
                    });
                    break;
            }
        },
        createDomDiv(id){
            var div = document.createElement('div');
            div.id = id;
            div.style = 'width:500px;height:500px;position:fixed;top:0;left:-99999;display:none;';
            document.body.append(div);
            switch (id) {
                case 'td_container':
                    wLeaflet.otherApi.params.loadTiandiMapJs.mapDiv = true;
                    break;
                case  'gaode_container':
                    wLeaflet.otherApi.params.loadGaodeMapJs.mapDiv = true;
                    break;
            }
        },
        //百度地图处理相关数据
        baiduMapFunc:{
            //初始化天地图 异步加载
            initMap:function(callback) {
                var _this = wLeaflet.otherApi;
                var wLeafletParams  = wLeaflet.params;
                if(_this.params.loadBaiduMapJs.status == false)
                {
                    var url = _this.params.loadBaiduMapJs.url.replace('{r_tk}',wLeafletParams.baiduKey);
                    var res = _this.loadJs(url,function () {
                        _this.params.loadBaiduMapJs.status = true;
                        if(typeof callback == 'function')
                        {
                            callback();
                        }
                    })
                }else{
                    if(typeof callback == 'function')
                    {
                        callback();
                    }
                }
            },
            //根据经纬度获取地理位置
            getLocation:function (latlng,callback) {
                this.initMap(function (res) {

                    var center = L.coordConver().gps84_To_bd09(latlng.lng, latlng.lat);//转换坐标点  放在高德地图中
                    var location = new BMap.Point(Number(center.lng), Number(center.lat));
                    var geoc = new BMap.Geocoder({extensions_town: true});
                    // 将给定的坐标位置转换为地址
                    geoc.getLocation(location,function (result) {
                        //console.log('result',result)
                        if(typeof callback == 'function')
                        {
                            if(result.surroundingPois && result.surroundingPois.length > 0)
                            {
                                var info = result.surroundingPois[0];
                                result.address = info.address + info.title;
                                result.point = info.point;
                            }
                            callback(result?result:{});
                        }
                    });
                });
            },
            getLocationSearch:function (title,callback) {
                var _this = wLeaflet.otherApi;
                var _tencentMapThis = this;
                _tencentMapThis.initMap(function (res) {
                    var mapDiv = _this.params.loadBaiduMapJs.mapDiv;
                    if(mapDiv == null)
                    {
                        wLeaflet.otherApi.createDomDiv('baidu_container');
                    }
                    var map = new BMap.Map("baidu_container");
                    var LngLat = wLeaflet.getMapInfo('getCenter');
                    var zoom = wLeaflet.getMapInfo('getZoom');
                    var center = L.coordConver().gps84_To_bd09(LngLat.lng, LngLat.lat);//转换坐标点  放在高德地图中
                    map.centerAndZoom(new BMap.Point(Number(center.lng), Number(center.lat)), zoom);
                    var local = new BMap.LocalSearch(map, {
                        //renderOptions:{map: map}
                        onSearchComplete:function(result){
                            var getPois = [];
                            if(result.Yr && result.Yr.length > 0)
                            {
                                getPois = result.Yr;
                                getPois.forEach(function (item) {
                                    //将高德的坐标转换   转换为能显示在leaflet里面的数据
                                    var center = L.coordConver().bd09_To_gps84(item.point.lng, item.point.lat); //转换坐标系
                                    item.latlng = {
                                        lat:center.lat,
                                        lng:center.lng,
                                    }
                                    item.name = item.address;
                                })
                            }
                            callback(getPois);
                        }
                    });
                    local.search(title);

                });
            }
        },
        //腾讯地图处理相关数据
        tencentMapFunc:{
            //初始化天地图 异步加载
            initMap:function(callback) {
                var _this = wLeaflet.otherApi;
                var wLeafletParams  = wLeaflet.params;
                if(_this.params.loadTencentMapJs.status == false)
                {
                    var url = _this.params.loadTencentMapJs.url.replace('{r_tk}',wLeafletParams.tencentKey);
                    var res = _this.loadJs(url,function () {
                        _this.params.loadTencentMapJs.status = true;
                        if(typeof callback == 'function')
                        {
                            callback();
                        }
                    })
                }else{
                    if(typeof callback == 'function')
                    {
                        callback();
                    }
                }
            },
            //根据经纬度获取地理位置
            getLocation:function (latlng,callback) {
                this.initMap(function (res) {
                    var center = L.coordConver().gps84_To_gcj02(latlng.lng, latlng.lat);//转换坐标点  放在高德地图中
                    var location = new TMap.LatLng(Number(center.lat), Number(center.lng));
                    var geocoder = new TMap.service.Geocoder();
                    // 将给定的坐标位置转换为地址
                    geocoder.getAddress({ location: location }).then((result) => {
                        //console.log(result);
                        if(typeof callback == 'function')
                        {
                            callback(result?result:{});
                        }
                        // 显示搜索到的地址
                    });
                });
            },
            getLocationSearch:function (title,callback) {
                var _this = wLeaflet.otherApi;
                var _tencentMapThis = this;
                _tencentMapThis.initMap(function (res) {
                    var mapDiv = _this.params.loadTencentMapJs.mapDiv;
                    if(mapDiv == null)
                    {
                        wLeaflet.otherApi.createDomDiv('tencent_container');
                    }
                    var LngLat = wLeaflet.getMapInfo('getCenter');
                    var zoom = wLeaflet.getMapInfo('getZoom');
                    var center = L.coordConver().gps84_To_gcj02(LngLat.lng, LngLat.lat);//转换坐标点  放在高德地图中
                    var search = new TMap.service.Search()
                    search.searchNearby({
                        keyword:title,
                        center:new TMap.LatLng(center.lat,center.lng),
                        radius:1000,
                        autoExtend:true
                    }).then(result=>{
                        var getPois = [];
                        if(result.data && result.data.length > 0)
                        {
                            getPois = result.data;
                            getPois.forEach(function (item) {
                                //将高德的坐标转换   转换为能显示在leaflet里面的数据
                                var center = L.coordConver().gcj02_To_gps84(item.location.lng, item.location.lat); //转换坐标系
                                item.latlng = {
                                    lat:center.lat,
                                    lng:center.lng,
                                }
                                item.name = item.address;
                            })
                        }
                        callback(getPois);
                    });
                });

            }
        },
        //高德地图处理相关数据
        gaodeMapFunc:{
            //初始化天地图 异步加载
            initMap:function(callback) {
                var _this = wLeaflet.otherApi;
                var wLeafletParams  = wLeaflet.params;
                if(_this.params.loadGaodeMapJs.status == false)
                {
                    window._AMapSecurityConfig = {
                        securityJsCode:wLeafletParams.gaodeSecurityJsCode,
                    }
                    var url = _this.params.loadGaodeMapJs.url.replace('{r_tk}',wLeafletParams.gaodeKey);
                    var res = _this.loadJs(url,function () {
                        _this.params.loadGaodeMapJs.status = true;
                        //console.log(AMap)
                        if(typeof callback == 'function')
                        {
                            callback();
                        }
                    })
                }else{
                    if(typeof callback == 'function')
                    {
                        callback();
                    }
                }
            },
            //根据经纬度获取地理位置
            getLocation:function (latlng,callback) {
                this.initMap(function (res) {
                    AMap.plugin('AMap.Geocoder', function() {
                        var geocoder = new AMap.Geocoder({
                            //city: '010'指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
                        })
                        var center = L.coordConver().gps84_To_gcj02(latlng.lng, latlng.lat);//转换坐标点  放在高德地图中
                        var lnglat = [center.lng,center.lat]
                        geocoder.getAddress(lnglat, function(status, result) {
                            if(typeof callback == 'function')
                            {
                                callback(result?result:{});
                            }
                        })
                    })
                });
            },
            getLocationSearch:function (title,callback) {
                var _this = wLeaflet.otherApi;
                var _gaodeMapThis = this;
                _gaodeMapThis.initMap(function (res) {
                    var mapDiv = _this.params.loadGaodeMapJs.mapDiv;
                    if(mapDiv == null)
                    {
                        wLeaflet.otherApi.createDomDiv('gaode_container');
                    }
                    var LngLat = wLeaflet.getMapInfo('getCenter');

                    var zoom = wLeaflet.getMapInfo('getZoom');
                    var center = L.coordConver().gps84_To_gcj02(LngLat.lng, LngLat.lat);//转换坐标点  放在高德地图中
                    var map = new AMap.Map('gaode_container', {
                        zoom:zoom,//级别
                        center: [center.lng, center.lat],//中心点坐标
                    });
                    AMap.service(["AMap.PlaceSearch"], function() {
                        //构造地点查询类
                        var placeSearch = new AMap.PlaceSearch({
                            pageSize: 10, // 单页显示结果条数
                            pageIndex: 1, // 页码
                            //city: "010", // 兴趣点城市
                            //citylimit: true,  //是否强制限制在设置的城市内搜索
                            map: map, // 展现结果的地图实例
                            //panel: "panel", // 结果列表将在此容器中进行展示。
                            autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
                        });
                        //关键字查询
                        placeSearch.search(title,function (status,result) {
                            var getPois = [];
                            if(result.info && result.info == 'OK')
                            {
                                var poiList = result.poiList?result.poiList:{};
                                getPois = poiList.pois?poiList.pois:[];
                                getPois.forEach(function (item) {
                                    //将高德的坐标转换   转换为能显示在leaflet里面的数据
                                    var center = L.coordConver().gcj02_To_gps84(item.location.lng, item.location.lat); //转换坐标系
                                    item.latlng = {
                                        lat:center.lat,
                                        lng:center.lng,
                                    }
                                })
                            }
                            callback(getPois);
                        });
                    });

                });

            }
        },
        tiandiMapFunc:{
            //初始化天地图 异步加载
            initMap:function (callback) {
                var _this = wLeaflet.otherApi;
                if(_this.params.loadTiandiMapJs.status == false)
                {
                    var url = _this.params.loadTiandiMapJs.url.replace('{r_tk}',wLeaflet.params.tdtKey);
                    var res = _this.loadJs(url,function () {
                        _this.params.loadTiandiMapJs.status = true;
                        if(typeof callback == 'function')
                        {
                            callback();
                        }
                    })
                }else{
                    if(typeof callback == 'function')
                    {
                        callback();
                    }
                }
            },
            //根据经纬度获取地理位置
            getLocation:function (latlng,callback) {
                this.initMap(function (res) {
                    var geocode = new T.Geocoder();
                    geocode.getLocation(new T.LngLat(latlng.lng,latlng.lat),function (result) {
                        if(typeof callback == 'function')
                        {
                            callback(result.result?result.result:{});
                        }
                    });
                });
            },
            getLocationSearch:function (title,callback) {
                var _this = wLeaflet.otherApi;
                var _tiandituThis = this;
                _tiandituThis.initMap(function (res) {
                    var mapDiv = _this.params.loadTiandiMapJs.mapDiv;
                    if(mapDiv == null)
                    {
                        wLeaflet.otherApi.createDomDiv('td_container');
                    }
                    map = new T.Map("td_container");
                    var LngLat = wLeaflet.getMapInfo('getCenter');
                    var zoom = wLeaflet.getMapInfo('getZoom');
                    //设置显示地图的中心点和级别
                    map.centerAndZoom(new T.LngLat(LngLat.lng, LngLat.lat), zoom);

                    var config = {
                        pageCapacity: 10,	//每页显示的数量
                        onSearchComplete: function (res) {
                            var getPois = [];
                            var resultType = res.resultType;
                            if(resultType == 3)
                            {
                                //返回地标类建筑 城市所在点
                                var area = res.getArea()
                                area.name = res.keyWord;
                                getPois.push(area)
                            }else if (resultType == 1){
                                //当resultType为1的时候  返回相关的搜索地址
                                getPois = res.getPois()
                            }
                            if(getPois.length > 0)
                            {
                                getPois.forEach(function (item) {
                                    if(resultType == 3)
                                    {
                                        var latlng = item.lonlat.split(',');
                                    }else if(resultType == 1)
                                    {
                                        var latlng = item.lonlat.split(' ');
                                    }
                                    item.latlng = {
                                        lat:latlng[1],
                                        lng:latlng[0]
                                    }
                                })
                            }
                            callback(getPois);
                        }	//接收数据的回调函数
                    };
                    //创建搜索对象
                    localsearch = new T.LocalSearch(map, config);
                    localsearch.search(title);

                });

            }
        }
    },
    plugins_leafletgeoman:{
        //插件地址https://github.com/geoman-io/leaflet-geoman#text-layer-drawing
        //可画类型 Currently available shapes are Marker, CircleMarker, Circle, Line, Rectangle, Polygon and Cut.
        //禁用绘画折线
        mapPmDisabled:function(){
            var _this = wLeaflet;
            _this.map.pm.disableDraw();
        },
        //折线编辑完成事件
        mapPmEditFinish:function(opeLayer,params){
            opeLayer.on('pm:update', (e) => {
                //console.log('update',e)
                opeLayer.removeEventListener("pm:update");
                if(typeof params.callback == 'function')
                {
                    params.callback(e);
                }
            });
            opeLayer.pm.disable();
        },
        //编辑折线类的layer
        mapPmEdit:function(opeLayer,params)
        {
            var _this = wLeaflet;
            opeLayer.setStyle({ pmIgnore: false }); //设置可拖动
            L.PM.reInitLayer(opeLayer);
            if(typeof params.onclickCallBack == 'function')
            {
                opeLayer.on('click',function () {
                    params.onclickCallBack(opeLayer)
                });
            }
            var enableDrawParams = {
                allowSelfIntersection:false,
                pathOptions:{},
            };
            if(params.hasOwnProperty('pathOptionsAddIndex') == true)
            {
                enableDrawParams.pathOptions.addIndex = params.pathOptionsAddIndex;
            }
            opeLayer.pm.enable(enableDrawParams);
            /*opeLayer.pm.enable({
                allowSelfIntersection: false,
            });*/
            return opeLayer;

        },
        //添加折线
        mapPmDraw:function(type,params){
            params = params?params:{};
            var _this = wLeaflet;
            _this.params.mapPmDrawParams.jsClass = type; //当前创造类型
            _this.params.mapPmDrawParams.drawMaxCount = (params.drawMaxCount && params.drawMaxCount > 0)?params.drawMaxCount:-1;
            _this.map.on('pm:create', (e) => {
                e.layer.setStyle({ pmIgnore: false });
                L.PM.reInitLayer(e.layer);
                _this.map.removeEventListener("pm:create");
                if(typeof params.onclickCallBack == 'function')
                {
                    e.layer.on('click',function () {
                        params.onclickCallBack(e.layer)
                    });
                }
                if(typeof params.callback == 'function')
                {
                    params.callback(e);
                }
            });
            var mapPm = _this.map.pm;
            var enableDrawParams = {
                allowSelfIntersection:params.allowSelfIntersection?params.allowSelfIntersection:false,
                pathOptions:{},
            };
            //路径颜色
            if(params.pathOptionsColor)
            {
                enableDrawParams.pathOptions = {
                    color:params.pathOptionsColor,
                    fillColor:params.pathOptionsColor,
                    fillOpacity: 0.7,
                };
            }
            if(params.hasOwnProperty('pathOptionsAddIndex') == true)
            {
                enableDrawParams.pathOptions.addIndex = params.pathOptionsAddIndex;
            }
            if(params.pathOptionsWeight)
            {
                enableDrawParams.pathOptions.weight = parseInt(params.pathOptionsWeight);
            }
            mapPm.enableDraw(type, enableDrawParams);
        },
        //经纬度创建折线
        createMapPmDraw:function (type,latlngArr,params) {
            var _this = wLeaflet;
            _this.params.mapPmDrawParams.jsClass = type; //当前创造类型
            params = params?params:{};
            var polyInitParams = {pmIgnore:true};
            var featureGroupParams = {};
            if(params.pathOptionsColor)
            {
                polyInitParams.color = params.pathOptionsColor; //边框颜色
            }
            if(params.pathOptionsFillColor)
            {
                polyInitParams.fillColor = params.pathOptionsFillColor; //填充底色的颜色
            }
            if(params.hasOwnProperty('pathOptionsAddIndex') == true)
            {
                polyInitParams.addIndex = params.pathOptionsAddIndex;
                featureGroupParams.addIndex = params.pathOptionsAddIndex;
            }
            if(type == 'Line')
            {
                var layerGroupItem = L.polyline(
                    latlngArr,
                    polyInitParams
                );
            }else if(type == 'Polygon')
            {
                var layerGroupItem = L.polygon(
                    latlngArr,
                    polyInitParams
                );
            }
            var setScopePolyline = L.featureGroup([layerGroupItem],featureGroupParams);

            //console.log('setScopePolyline',setScopePolyline)
            setScopePolyline.on('click',function () {
                params.clickCallback = params.clickCallback?params.clickCallback:'';
                if(typeof params.clickCallback == 'function')
                {
                    params.clickCallback(setScopePolyline);
                }else if(params.clickCallback == 'remove')
                {
                    setScopePolyline.remove();
                }
            })
            setScopePolyline.addTo(_this.map);
            return setScopePolyline;
        }
    },
    //声明开始标记marker点
    createMarker:function (latlng,params) {
        params = params?params:{};
        var iconUrl = params.iconUrl?params.iconUrl:this.params.markerImage;
        var iconSize = params.iconSize?params.iconSize:this.params.markerImageSize;
        var myIcon = L.icon({
            iconUrl: iconUrl,
            iconSize: iconSize,
        });
        var marker = L.marker([latlng.lat, latlng.lng],{
            icon:myIcon
        });
        if(params.bindTooltipContent)
        {
            var bindTooltipObj = {
                permanent : (('permanent' in params) && params.permanent == false)?false:true,//是永久打开工具提示还是只在鼠标移动时打开。
                //direction 打开工具提示的方向。可能的值有：right、left、 top、bottom、center、auto。 auto 将之间进行动态切换 right 和 left 根据地图上的工具提示位置。
                direction : (params.direction)?params.direction:'auto',
            };
            if(params.setOffset)
            {
                var point = L.point(params.setOffset[0], params.setOffset[1]);
                bindTooltipObj.point = point;
            }
            marker.bindTooltip(params.bindTooltipContent,bindTooltipObj).openTooltip();
        }
        marker.on('click',function () {
            params.clickCallback = params.clickCallback?params.clickCallback:'';
            if(typeof params.clickCallback == 'function')
            {
                params.clickCallback(marker);
            }else if(params.clickCallback == 'remove')
            {
                marker.remove();
            }
        }).addTo(this.map);
        if(params.needSetView && params.needSetView == true)
        {
            this.setMapView(latlng.lat,latlng.lng);
        }
        return marker;
    },
    //设置地图定位和缩放缩放等级
    setMapView(lat,lng,zoom){
        var latlng = L.latLng(lat, lng);
        zoom = zoom?zoom:this.map.getZoom();
        this.map.setView(latlng,zoom);
    },
    //获取地图信息
    getMapInfo(funcName){
        if(!funcName)
        {
            return '';
        }
        if(this.map[funcName] && typeof this.map[funcName] == 'function')
        {
            return this.map[funcName]();
        }
    },
    //移除marker等添加的覆盖物点
    removeAppendFunc:function(obj){
        try{
            obj.remove();
        }catch (e) {
            console.log('删除覆盖物失败',e);
        }
    },
    //注册点击地图事件
    addMapClick:function(callback)
    {
        var _this = this;
        if(callback)
        {
            _this.params.mapClickCallbackFunc = callback;
        }
        _this.removeMapClick();
        _this.map.addEventListener("click",_this.mapClickRes);
    },
    //移除点击事件
    removeMapClick:function()
    {
        this.map.removeEventListener("click",this.mapClickRes);
    },
    //点图点击返回结果 mapClickCallback由用户自定义
    mapClickRes:function(e)
    {
        var mapClickCallbackFunc = wLeaflet.params.mapClickCallbackFunc;
        if(typeof mapClickCallbackFunc == 'function')
        {
            mapClickCallbackFunc(e);
        }
    },
    //创建手绘图
    createHandImage:function (latlngArr,imgUrl){
        var bd = latlngArr;
        var handImage = new L.imageOverlay(imgUrl, bd, {
            opacity: 1,
            alt: "手绘图"+imgUrl
        });
        handImage.addTo(this.map);
        return handImage;
    },
    //创建显示瓦片图
    createTileLayerByTileUrl:function (tilesUrl) {
        var _this = this;
        L.TileLayer.T = L.TileLayer.extend({
            getTileUrl: function (c) {
                var mapUrl = tilesUrl.replaceAll("{x}", c.x)
                    .replaceAll("{y}", c.y)
                    .replaceAll("{z}", c.z);
                return mapUrl;
            }
        });
        var tileM = new L.TileLayer.T();
        tileM.setZIndex(99999);
        _this.map.addLayer(tileM);
        return tileM;
    },
    //移除加载出来的瓦片图
    removeTileLayerByTileLayer:function (tileLayer) {
        this.map.removeLayer(tileLayer);
    }

};



